package com.fable.web.interceptor;

import com.alibaba.fastjson.JSON;
import com.fable.biz.operate.UserLogService;
import com.fable.common.constant.FableConstant;
import com.fable.dal.dto.AdminUserDTO;
import com.fable.dal.model.AdminDO;
import com.fable.dal.model.AdminUserDO;
import com.fable.dal.model.UserLogDO;
import com.fable.web.common.admin.UserTools;
import com.fable.web.common.annotation.Track;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 拦截并配置加载当前登录用户，静态资源，以及velocity模板对象
 */
public class TrackInterceptor extends HandlerInterceptorAdapter implements InitializingBean {

    private static final Logger log = LoggerFactory.getLogger(TrackInterceptor.class);
    @Autowired
    UserLogService userLogService;

    @Override
    public void afterPropertiesSet() throws Exception {
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //埋点跟踪
        if (modelAndView != null && modelAndView.getViewName() != null && !modelAndView.getViewName().startsWith("redirect:")) {
            handlerTrack(request, handler);
        }
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;
    }


    /**
     * 判断是否需要登录验证
     */
    private void handlerTrack(HttpServletRequest request, Object handler) {
        try {
            if (handler instanceof HandlerMethod) {
                HandlerMethod mHandler = (HandlerMethod) handler;
                Class<?> beanClass = mHandler.getBeanType();
                //注解在类上标注不做处理，只处理作用在方法上
                if (beanClass.isAnnotationPresent(Track.class)) {
                    return;
                } else {
                    Track trackAnnotation = mHandler.getMethodAnnotation(Track.class);
                    if (trackAnnotation != null) {
                        StringBuffer sb = new StringBuffer();
                        Map<String, String[]> map = request.getParameterMap();
                        if (!CollectionUtils.isEmpty(map)) {
                            try {
                                Map m = new HashMap();
                                //过滤map里的非空key或空value
                                for (Map.Entry entry : map.entrySet()) {
                                    if (!StringUtils.isBlank((String) entry.getKey()) && !CollectionUtils.isEmpty(Arrays.asList(entry.getValue())) && StringUtils.isNotBlank(((String[]) entry.getValue())[0])) {
                                        m.put(entry.getKey(), ((String[]) entry.getValue())[0]);
                                    }
                                }
                                sb.append(JSON.toJSONString(m));
                            } catch (Exception e) {
                                log.error("filter error in map,  null key or value ");
                                sb.append(JSON.toJSONString(map));
                            }
                        }
                        HttpSession session = request.getSession();
                        AdminUserDTO admin = UserTools.getAdminUser(session);
                        if (admin != null) {
                            UserLogDO userLogDO = new UserLogDO();
                            userLogDO.setGmtModified(new Date());
                            userLogDO.setAct(trackAnnotation.tag().getName());
                            userLogDO.setUserId(admin.getId());
                            userLogDO.setUserName(admin.getNick());
                            userLogDO.setGmtCreate(new Date());
                            userLogDO.setAct(trackAnnotation.tag().getName());
                            userLogDO.setParams(sb.toString());
                            userLogDO.setUrl(trackAnnotation.tag().getUrl());
                            userLogService.addLog(userLogDO);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("error in handlerTrack", e);
        }
    }

    /**
     * 获取登陆者id
     *
     * @return
     */
    private Long getLoginId(HttpServletRequest request) {
        HttpSession session = request.getSession();
        AdminDO admin = (AdminDO) session.getAttribute(FableConstant.USER_SESSION_KEY);
        if (admin != null) {
            return admin.getAdminId();
        }
        return 0L;

    }

}
